#pragma once

#include "event_router.hpp"
#include "module.hpp"
#include "accelerator.hpp"

namespace winboost {
   namespace thread {

class win_thread : public events::event_router
{
public:
   win_thread(void);

   resources::accelerator& accelerator(void) const;

   //-------------------------------------------
   // Main window for this thread. When last window
   // destroyed, thread exits.
   //-------------------------------------------
   void set_main_window(resources::win_handle* p) { m_pwnd_main = p; }
   int run(void);

protected:
   resources::accelerator m_accelerator;
   resources::win_handle* m_pwnd_main;

   //-------------------------------------------
   // application specific initialization
   //-------------------------------------------
   virtual void init_instance(){}

   //-------------------------------------------
   // return application exit code
   //-------------------------------------------
   virtual int exit_instance(int exit_code) { return exit_code; }

private:
   virtual int run_impl(void);
};



//-------------------------------------
// implementation
//-------------------------------------
inline win_thread::win_thread(void):
  m_pwnd_main(NULL)
{
}

inline winboost::resources::accelerator& win_thread::accelerator(void) const 
{ 
   return const_cast<winboost::resources::accelerator&>(m_accelerator);
}

inline int win_thread::run(void)
{
   init_instance();
   int result = run_impl();
   return exit_instance(result);
}

inline int win_thread::run_impl(void)
{
   MSG msg;
   while (::GetMessage(&msg, NULL, 0, 0))
   {
      //Check if we need to handle MDI accelerators
      if(::IsWindow(_the_module.m_hmdiclient))
      {
         if(::TranslateMDISysAccel (_the_module.m_hmdiclient, &msg))
            continue;
      }
      
      if(m_accelerator.handle())
      {
         if(::TranslateAccelerator(msg.hwnd, m_accelerator.handle(), &msg))
            continue;
      }

      ::TranslateMessage(&msg);
      ::DispatchMessage(&msg);
   }
   return (int) msg.wParam;
}


   }
}



